package com.fusion.core.comm.rpc;

import com.fusion.core.T;
import com.fusion.core.comm.Packet;
import com.fusion.core.comm.RPC;
import com.fusion.core.file.filedatabase.FileDescriptor;
import com.fusion.core.file.filedatabase.FileType;

import java.io.IOException;

/**
 * @author SwethaShivakumar 
 * Project: fusion
 * Date: Mar 6, 2009
 * URL: http://fusionwiki.co.cc
 * Mail Me At: shiva@fusionproject.co.cc
 */
public class Search extends RPC {
    private String query;
    private byte fileTypeId;

    public Search() {
    }

    public Search(String query, byte fileTypeId) {
        this();
        this.query = query;
        this.fileTypeId = fileTypeId;
    }

    public void execute(Packet in) throws IOException {
        query = in.readUTF();

        core.logNetworkEvent("Search query "+query+" from "+con.getRemoteFriend());
        
        FileType ft = FileType.EVERYTHING;
        int ftid = in.readByte();
        if (FileType.getFileTypeById(ftid) != null) ft = FileType.getFileTypeById(ftid);

        FileDescriptor fd[] = manager.getCore().getFileManager().search(query, SearchHits.MAX_SEARCH_HITS, ft);
        SearchHitsV2 sh = new SearchHitsV2();
        for(FileDescriptor f : fd) if (f != null) sh.addHit(f);

        if(T.t)T.info("Found "+sh.getNHits()+" hits.");
        if (sh.getNHits() > 0) {
            //reply with Search hits
            send(fromGuid, sh);
        }
    }

    public Packet serializeTo(Packet p) {
        p.writeUTF(query);
        p.writeByte(fileTypeId);
        return p;
    }
}
